<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form ref="queryForm" :model="queryForm" inline :label-width="70">
          <Form-item label="角色名称" prop="roleName">
            <Input
              type="text"
              v-model="queryForm.roleName"
              clearable
              placeholder="请输入角色名称"
              style="width: 200px"
            />
          </Form-item>
          <Form-item style="margin-left:-35px;" class="br">
            <Button @click="handleSearch" type="primary" size="large" icon="ios-search">搜索</Button>
            <Button @click="handleReset" size="large">重置</Button>
          </Form-item>
        </Form>
      </Row>
      <Row class="operation">
        <Button @click="add" size="large" type="primary" icon="md-add">添加</Button>
        <Button @click="delAll" size="large" icon="md-trash">删除</Button>
      </Row>
      <Row>
        <Alert show-icon>
          已选择
          <span class="select-count">{{selectCount}}</span> 项
          <a class="select-clear" @click="clearSelectAll">清空</a>
        </Alert>
      </Row>
      <Row>
        <Table
          :loading="loading"
          border
          :columns="columns"
          :data="data"
          sortable="custom"
          @on-sort-change="changeSort"
          @on-selection-change="showSelect"
          ref="table"
        ></Table>
      </Row>
      <Row type="flex" justify="end" class="page">
        <Page
          :current="queryForm.pageNum"
          :total="total"
          :page-size="queryForm.pageSize"
          @on-change="changePageNum"
          @on-page-size-change="changePageSize"
          :page-size-opts="[10,20,50]"
          size="small"
          show-total
          show-elevator
          show-sizer
        ></Page>
      </Row>
      <RoleForm ref="roleForm" @ok="submitOk"></RoleForm>
      <Modal
        :title="permissionTitle"
        v-model="permissionVisible"
        width="500"
        class="menuModal"
        :mask-closable="false"
      >
        <div style="position:relative">
          <Tree :data="menuData" show-checkbox :check-strictly="true" ref="menuTree"  style="margin-top:15px"></Tree>
          <Spin size="large" fix v-if="treeLoading"></Spin>
        </div>
        <div class="demo-drawer-footer">
          <Button style="margin-right: 8px" type="text" @click="permissionVisible = false">取 消</Button>
          <Button style="margin-right: 8px" @click="selectTreeAll">全选/反选</Button>
          <Button type="primary" @loading="permissionLoading" @click="submitPermission">提 交</Button>
        </div>
      </Modal>
    </Card>
  </div>
</template>

<script>
import RoleForm from "@/view/admin/form/RoleForm";
import {queryRoleList,deleteRole,saveRolePermission} from "@/api/role";
import {getMenuList} from "@/api/menu";
export default {
  name: "Role",
  components:{
    RoleForm
  },
  data(){
    return{
      queryForm:{
        pageNum: 1,
        pageSize: 10,
        roleName:''
      },
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static',
      },
      loading:false,
      total:null,
      permissionVisible:false,
      menuData:[],
      treeLoading:false,
      selectAllFlag:false,
      permissionLoading:false,
      permissionTitle:'设置权限',
      roleId:null,
      columns:[
        {
          type: "selection",
          width: 60,
          align: "center",
          fixed: "left"
        },
        {
          type: "index",
          width: 60,
          align: "center",
          fixed: "left"
        },
        {
          title: "角色名称",
          key: "roleName",
          align: 'center',
          minWidth: 100,
          sortable: true,
        },
        {
          title: "角色编码",
          key: "roleCode",
          align: "center",
          minWidth: 100,
        },
        {
          title: "创建时间",
          key: "createTime",
          sortable: true,
          align: 'center',
          minWidth: 100,
        },
        {
          title: "操作",
          key: "action",
          align: 'center',
          width: 300,
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "success",
                    size: "small",
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.setPermission(params.row);
                    }
                  }
                },
                " 设置权限"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.row);
                    }
                  }
                },
                " 编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.del(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        },
      ],
      selectCount:0,
      selectList:[],
      data:[],
    }
  },
  methods:{
    handleSearch(){
      this.getRoleList();
    },
    clearSelectAll(){
      this.selectList=[];
      this.selectCount=0
      this.$refs.table.selectAll(false);
    },
    changePageNum(v){
      this.queryForm.pageNum=v;
      this.getRoleList();
    },
    selectTreeAll(){
      this.selectAllFlag = !this.selectAllFlag;
      let select = this.selectAllFlag;
      this.selectAllMenu(this.menuData,select)
    },
    setPermission(row){
      this.permissionVisible=true;
      this.roleId=row.roleId;
      this.permissionTitle='设置【'+row.roleName+'】菜单权限';
      let roleMenuIds=row.roleMenuIds;
      this.checkPermissionChecked(this.menuData,roleMenuIds)
    },
    submitPermission(){
      let checkedNodes = this.$refs['menuTree'].getCheckedNodes();
      if(checkedNodes.length<=0){
         this.$Message.warning('请选择要设置的权限')
         return ;
      }
      let permissionIds=[];
      for(let obj of checkedNodes){
         permissionIds.push(obj.menuId);
      }
      let formData={roleId:this.roleId,permissionIds:permissionIds};
      this.permissionLoading=true;
      saveRolePermission(formData).then(res=>{
          if(res.code===200){
             this.permissionLoading=false;
             this.permissionVisible=false;
             this.$Message.success('权限设置成功');
             this.getRoleList();
             this.roleId='';
          }
      })
    },
    selectAllMenu(permData, select) {
      let that = this;
      permData.forEach(function(e) {
        that.$set(e,'checked',select)
        that.$set(e,'expand',true)
        if (e.children && e.children.length > 0) {
          that.selectAllMenu(e.children, select);
        }
      });
    },
    submitOk(){
      this.getRoleList();
    },
    changePageSize(value) {
      this.queryForm.pageSize=value;
      this.getRoleList();
    },
    changeSort(){

    },
    initMenuData(){
      this.treeLoading=true;
      getMenuList().then(res=>{
        if(res.code===200){
           this.treeLoading=false;
           this.menuData=res.data;
        }
      })
    },
    checkPermissionChecked(permData,rolePerm){
      let that=this;
      if(rolePerm.length>0){
        permData.forEach(function(p){
          if(that.isCheckedPermission(p,rolePerm)){
            that.$set(p,'checked',true)
          }else{
            that.$set(p,'checked',false)
          }
          if(p.children&&p.children.length>0){
            that.checkPermissionChecked(p.children,rolePerm);
          }
        })
      }
    },
    isCheckedPermission(p,rolePerm){
      let flag=false;
      for(let i=0;i<rolePerm.length;i++){
         if(p.menuId===rolePerm[i]){
            flag=true;
            break;
         }
      }
      if(flag){
        return true;
      }
      return false;
    },
    showSelect(v){
      this.selectCount=v.length;
      this.selectList=v;
    },
    add(){
      this.$refs['roleForm'].add();
      this.$refs['roleForm'].title='添加角色';
      this.$refs['roleForm'].modalType=1;
    },
    del(row){
      this.selectCount = 1;
      this.selectList.push(row);
      this.delAll();
    },
    delAll(){
      let that=this;
      if(that.selectList.length<=0){
         this.$Message.warning('请至少选择一条数据');
         return ;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content:"您确认要删除所选的 " + this.selectCount + " 条数据?",
        loading: true,
        onOk: () => {
          let data=this.selectList;
          let ids='';
          data.forEach(e=>{
            ids+=e.roleId+','
          })
          ids=ids.substring(0,ids.length-1);
          deleteRole(ids).then(res=>{
            if(res.code===200){
              this.$Message.success('操作成功');
            }
            this.getRoleList();
            this.selectList = [];
            this.selectCount = 0;
            this.$Modal.remove()
          })
        }
      });
    },
    edit(row){
      this.$refs['roleForm'].edit(row);
      this.$refs['roleForm'].title='编辑角色';
      this.$refs['roleForm'].modalType=2;
    },
    handleReset(){
      this.$refs['queryForm'].resetFields();
      this.getRoleList();
    },
    getRoleList() {
      this.loading=true
      queryRoleList(this.queryForm).then(res=>{
        if(res.code===200){
           this.data=res.data.records;
           this.total=res.data.total;
           this.loading=false;
        }
      })
    }
  },
  mounted(){
    this.getRoleList();
    this.initMenuData();
  }
}
</script>

<style lang="less">
@import "../../styles/table-common.less";
.demo-drawer-footer{
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
.menuModal{
  .ivu-modal-body{
    max-height: 550px;
    overflow: auto;
    font-size: 12px;
    line-height: 1.5;
    padding: 16px;
  }
}
</style>
